import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

/**
 * @author by zyl
 * @date 2020/3/28.
 */
public class Registry {
    private static ECPoint P;
    private static ECPoint PK;
    private static ECCOperator ec;

    static {
        ec=new ECCOperator();
        ECPoint G=new ECPoint(new BigInteger("2"),new BigInteger("4"));
        P=ec.multiply(G,new BigInteger("123456"));
        String sPK= FileUtil.readTag(CommonValue.KeyTable,"KGC").split(" ")[1];
        PK=new ECPoint(new BigInteger(sPK.split(",")[0]),new BigInteger(sPK.split(",")[1]));
    }


    public static void askKey(){
        String rc=CharacterUtils.getRandomInteger(16);
        System.out.println("Generating ra:"+rc);
        ECPoint RC=ec.multiply(P,new BigInteger(rc));
        System.out.println("Computing RA:"+RC.toString());
        String uIDA=FileUtil.readTag(CommonValue.IDTable,"A").split(" ")[1];
        ECPoint ck=ec.multiply(PK,new BigInteger(rc));
        String eck=Base64.encode(XorUtils.xor(uIDA,ck.toString()));
        SocketUtils.out(CommonValue.A_KGC_IP,CommonValue.KGC_PORT,eck+":"+RC.toString());
        String received=SocketUtils.in(CommonValue.KGC_A_PORT);
        String results=XorUtils.xor(Base64.decode(received),ck.toString());
        System.out.println("receiving results:"+results);
        String IDC=results.split(":")[0];
        String IDB=results.split(":")[1];
        String KCij=results.split(":")[2];
        String KB=results.split(":")[3];
        String KA=results.split(":")[4];
        Map<String,String> idMap=new HashMap<String,String>();
        idMap.put("B1",IDB);
        idMap.put("C11",IDC);
        System.out.println("receiving B1:"+IDB+", C11:"+IDC);
        Map<String,String> keyMap=new HashMap<String,String>();
        keyMap.put("C11",KCij);
        keyMap.put("B1",KB);
        keyMap.put("A",KA);
        System.out.println("receiving KC11:"+KCij+" KB1:"+KB+" KA:"+KA);
        FileUtil.writeLine(CommonValue.IDTable,idMap);
        FileUtil.writeLine(CommonValue.KeyTable,keyMap);
    }

    public static void main(String args[]){
        askKey();
    }

}